local desc_joy1v2 = [[
  # 欢杀斗地主模式简介

  ___

  不支持双将

  起始5牌，移除宝物区（开启副将按钮会保留宝物区）

  地主农民同时选将，农民互通选将框，地主将框加入3个地主专属将，全部选择完毕后明置武将

  农民互通手牌。
]]


-- Because packages are loaded before gamelogic.lua loaded
-- so we can not directly create subclass of gamelogic in the top of lua

local dizhu = {"gundam","longwang","wuzixu","libai","khan","zhutiexiong","tycl__caocao","tycl__liubei","tycl__sunquan","sunwukong","nezha","tycl__sunce","tycl__wuyi","joyo__libai","joyo__change","joyo__nvwa","joyo__xiaoshan","joyo__khan","joyo__heili","goddianwei","child__sunquan","quyuan","joyo__dalanmao"}
local joy_1v2_getLogic = function()
  local joy_1v2_logic = GameLogic:subclass("joy_1v2_logic")

  function joy_1v2_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = {nil, nil, {"lord", "rebel", "rebel"}}
  end

  function joy_1v2_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = math.min(room.settings.generalNum, 9)
    for _, p in ipairs(room.players) do
      p.role_shown = true
      room:broadcastProperty(p, "role")
    end
    local dzhu = {}
    for _, g in ipairs(dizhu) do
      if table.contains(room.general_pile,g) then
        table.removeOne(room.general_pile,g)
        table.insertIfNeed(dzhu,g)
      end
    end
    local lord = room:getLord()
    room.current = lord
    local nonlord = {}
    for _, p in ipairs(room.players) do
      if p.role ~= "lord" then
        table.insert(nonlord,p)
      end
    end
    -- 地主多发俩武将
    local generals = table.map(Fk:getGeneralsRandomly(3 * generalNum), Util.NameMapper)
    table.shuffle(generals)
    local t1 = table.slice(generals, 1, generalNum + 1)
    local t2 = table.slice(generals, generalNum + 1, generalNum * 2 + 1)
    local gens = table.slice(generals, generalNum*2 + 1, generalNum * 3 + 1)
    if #dzhu > 0 then
      table.insertTableIfNeed(gens,table.random(dzhu,3))
    end
    lord.request_data = json.encode({ gens, 1 })
    lord.default_reply = gens[1]
    local game = Fk.mini_games["2v2_sel"]
    local data_table = {
      [nonlord[1].id] = {
        friend_id = nonlord[2].id,
        me = t1, friend = t2,
      },
      [nonlord[2].id] = {
        friend_id = nonlord[1].id,
        me = t2, friend = t1,
      },
    }
    for _, p in ipairs(nonlord) do
      local data = data_table[p.id]
      p.mini_game_data = { type = "2v2_sel", data = data }
      p.request_data = json.encode(p.mini_game_data)
      p.default_reply = game.default_choice and json.encode(game.default_choice(p, data)) or ""
    end
    
    room:notifyMoveFocus(room.players, "选择武将")

    room.request_queue = {}
    room.race_request_list = nil
    local function setRequestTimer(room1)
      room1.room:setRequestTimer(room1.timeout * 1000 + 500)
    end
    setRequestTimer(room)
    if lord then
      lord:doRequest("AskForGeneral", lord.request_data)
    end
    for _, p in ipairs(nonlord) do
      p:doRequest("MiniGame", p.request_data)
    end
    local remainTime = room.timeout
    local currentTime = os.time()
    local elapsed = 0
    for _, p in ipairs(room.players) do
      elapsed = os.time() - currentTime
      p:waitForReply(remainTime - elapsed)
    end
    for _, p in ipairs(room.players) do
      p.serverplayer:setBusy(false)
      p.serverplayer:setThinking(false)
    end
    room.room:destroyRequestTimer()
    local function surrenderCheck(room2)
      if not room2.hasSurrendered then return end
      local player = table.find(room2.players, function(p)
        return p.surrendered
      end)
      if not player then
        room2.hasSurrendered = false
        return
      end
      room2:broadcastProperty(player, "surrendered")
      local mode = Fk.game_modes[room2.settings.gameMode]
      local winner = Pcall(mode.getWinner, mode, player)
      if winner ~= "" then
        room2:gameOver(winner)
      end
    
      -- 以防万一
      player.surrendered = false
      room2:broadcastProperty(player, "surrendered")
      room2.hasSurrendered = false
    end
    surrenderCheck(room)
    for _, p in ipairs(nonlord) do
      p.mini_game_data = nil
      if not p.reply_ready then
        p.client_reply = p.default_reply
        p.reply_ready = true
      end
    end
    for _, p in ipairs(nonlord) do
      local general = json.decode(p.client_reply)
      room:setPlayerGeneral(p, general, true, true)
    end
    if lord then
    if lord.general == "" and lord.reply_ready then
      local general = json.decode(lord.client_reply)[1]
      room:setPlayerGeneral(lord, general, true, true)
    else
      room:setPlayerGeneral(lord, lord.default_reply, true, true)
    end
    lord.default_reply = ""
    table.removeOne(gens,lord.general)
    end
    room:returnToGeneralPile(gens)

    local rebel = {}
    for _, p in ipairs(room.players) do
      if p.role ~= "lord" then
        table.insert(rebel,p)
      end
    end
    for _, p in ipairs(rebel) do
      for _, p2 in ipairs(rebel) do
        if p2 ~= p then
          p:addBuddy(p2)
        end
      end
    end
    room:askForChooseKingdom(room.players)
    for _, p in ipairs(room.players) do
      room:broadcastProperty(p, "role")
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
    end
  end

  return joy_1v2_logic
end

local joy_1v2_rule = fk.CreateTriggerSkill{
  name = "#joy_1v2_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart, fk.Deathed,fk.DrawInitialCards,fk.GamePrepared},
  can_refresh = function(self, event, target, player, data)
    if event == fk.Deathed then
      return target == player and player.rest == 0
    elseif event == fk.DrawInitialCards then
      return target == player
    elseif event == fk.GamePrepared then
      return true
    elseif event == fk.GameStart  then
      return player.role == "lord"
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      room:handleAddLoseSkills(player, "m_feiyang|m_bahu", nil, false)
      if player.general ~= "gundam" then
        player.maxHp = player.maxHp + 1
        player.hp = player.hp + 1
        room:broadcastProperty(player, "maxHp")
        room:broadcastProperty(player, "hp")
      end
      room:setTag("SkipNormalDeathProcess", true)
    elseif event == fk.Deathed then
      for _, p in ipairs(room.alive_players) do
        if p.role == "rebel" then
          local choices = {"m_1v2_draw2", "Cancel"}
          if p:isWounded() then
            table.insert(choices, 2, "m_1v2_heal")
          end
          local choice = room:askForChoice(p, choices, self.name)
          if choice == "m_1v2_draw2" then p:drawCards(2, self.name)
          else room:recover{ who = p, num = 1, skillName = self.name } end
        end
      end
    elseif event == fk.DrawInitialCards then
      data.num = data.num + 1
    elseif event == fk.GamePrepared then
      if not room.settings.enableDeputy then
        for _, p in ipairs(room.alive_players) do
          table.removeOne(p.equipSlots, Player.TreasureSlot)
        end
      else
        room:doBroadcastNotify("ShowToast","已开启副将按钮，保留角色宝物栏。")
      end
    end
  end,
}
Fk:addSkill(joy_1v2_rule)
local joy_1v2_mode = fk.CreateGameMode{
  name = "joy_1v2_mode",
  minPlayer = 3,
  maxPlayer = 3,
  rule = joy_1v2_rule,
  logic = joy_1v2_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 2 min", passed = playedTime >= 120 } }
    if Self.role ~= "lord" then
      table.insert(
        surrenderJudge,
        { text = "1v2: left you alive", passed = #table.filter(Fk:currentRoom().players, function(p) return p.rest > 0 or not p.dead end) == 2 }
      )
    end

    return surrenderJudge
  end,
}

Fk:loadTranslationTable{
  ["joy_1v2_mode"] = "欢杀斗地主",
  ["#joy_1v2_rule"] = "农民补贴",

  [":joy_1v2_mode"] = desc_joy1v2,
}

return joy_1v2_mode
